import headeBar from '../../components/headeBar.vue'
import sidebar from '../../components/sidebar.vue'

import {getStockOverview,
        postOperationRecord,
        getOperationRecordData} from '../../api'
import {saveToken, saveUserinfo} from "../../utils";

export default {
  name: "overview",
  data() {
    // 校验操作数量
    var checkCount = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('数量不能为空'));
      }
      if (value === '0') {
        return callback(new Error('数量不能为0'))
      }
    };
    // 校验操作类型
    var checkType = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请选择入库或出库'));
      }
    };
    return {
      activeIndex: 'overview',
      tableData: [],    // 库存数据
      currentCompenent: '',    // 当前选中的零件名
      currentCompenentUnit:'',    // 当前选中的零件的计量单位
      addRecordDialogVisible: false,    // 增加记录模态框
      viewRecordDialogVisible: false,    // 查看历史记录模态框
      viewMemoDialogVisable: false,    //查看备注模态框
      operationRecordData: [],    // 某个库存的历史记录
      memo: '',    // 当前选中历史记录的备注
      ifAddRecordFlag: false,    // 判断是否有未处理完的操作

      // 新增记录表单
      addRecordForm: {
        stock: '',    // 库存
        count: '',    // 数量
        type: '',    // 进货还是出货
        memo: '',    // 备注
        stockID: '',    // 库存id
      },

      // 新增记录表单校验规则
      addRecordRules: {
        count: [
          { validator: checkCount, trigger: 'blur' }
        ],
        type: [
          { validator: checkType, trigger: 'blur' }
        ]
      }

    };
  },
  methods: {
    // 获取库存总览
    async getTableData(){
      let res  = await getStockOverview();
      if(res.status===200){    // 登录成功,保存token,保存用户基本信息
        this.tableData = res.data;
      }else if(res.status === 401 || res.status === 403){    // 登录超时，跳转到登录页
        this.$router.push({path: '/login',query:{to:this.$route.path}});
      }else{    // 提示错误消息
        this.$message.error(res.data.non_field_errors[0]);
      }
    },

    // 标记小于警戒值的库存
    tableRowClass({row, rowIndex}) {
      if (row.stock ===0) {
        return 'error-row';
      }else if (row.stock < row.threshold){
        return 'warning-row';
      }
      return '';
    },

    // 标记入库和出库
    recordRowClass({row, rowIndex}) {
      if (row.type === '入库') {
        return 'in-row';
      }else if (row.type === '出库'){
        return 'out-row';
      }else if (row.type === '初始化'){
        return 'init-row';
      }
      return '';
    },

    // 点击添加记录
    addRecord(scope){
      this.currentCompenent = scope.row.name;
      this.currentCompenentUnit = scope.row.unit;

      this.addRecordForm.stock = scope.row.stock;
      this.addRecordForm.stockID = scope.row.id;
      this.addRecordForm.count = '';
      this.addRecordForm.type = '';
      this.addRecordForm.memo = '';

      this.addRecordDialogVisible = true;

    },

    // 提交新增记录表单
    async postRecordForm(){
      //防止重复提交
      if(this.ifAddRecordFlag){
        this.$message.warning('正在处理，请不要重复提交');
        return
      }
      // 判断信息是否完整
      if( !this.addRecordForm.stockID || !this.addRecordForm.count || !this.addRecordForm.type){
        this.$message.error('输入有误，请核对信息');
        return
      }else {
        this.addRecordForm.count = parseInt(this.addRecordForm.count);
        this.addRecordForm.stock = parseInt(this.addRecordForm.stock);
        if(this.addRecordForm.type ==='2' && (this.addRecordForm.count > this.addRecordForm.stock)){
          this.$message.error('出库数量不能大于库存');
          return
        }
      }
      // 开始提交数据
      this.ifAddRecordFlag = true;
      let data = {
        count: this.addRecordForm.count,
        operation_type: this.addRecordForm.type,
        memo: this.addRecordForm.memo,
        stock_id: this.addRecordForm.stockID,
      };
      let res = await postOperationRecord(data);
      this.ifAddRecordFlag = false;
      if(res.status===201){
        this.getTableData();
        this.$message.success('操作成功');
        this.addRecordDialogVisible = false;
      }else if(res.status === 401 || res.status === 403){    // 登录超时，跳转到登录页
        this.$router.push({path: '/login',query:{to:this.$route.path}});
      }else{    // 提示错误消息
        if(res.data.non_field_errors){
          this.$message.error(res.data.non_field_errors[0]);
        }else{
          this.$message.error(res.data.detail);
        }

      }
    },


    // 正则校验，只允许输入正整数
    allowNumber(){
      this.addRecordForm.count=this.addRecordForm.count.replace(/[^\.\d]/g,'');
      this.addRecordForm.count=this.addRecordForm.count.replace('.','');
    },

    // 点击查看历史记录
    async viewRecord(scope){
      this.currentCompenent = scope.row.name;
      let res = await getOperationRecordData(scope.row.id);
      if(res.status===200){
        this.operationRecordData = res.data.map(function (item) {
          if(item.type==='1'){
            item.type = '入库';
          }else if(item.type === '2'){
            item.type = '出库';
          }else if(item.type === '3'){
            item.type = '初始化';
          }
          return item;
        });
        this.viewRecordDialogVisible = true;
      }else if(res.status === 401 || res.status === 403){    // 登录超时，跳转到登录页
        this.$router.push({path: '/login',query:{to:this.$route.path}});
      }else{
        if(res.data.non_field_errors){
          this.$message.error(res.data.non_field_errors[0]);
        }else{
          this.$message.error(res.detail);
        }
      }
    },

    // 点击显示备注
    viewMemoDialog(scope){
      this.memo = scope.row.memo;
      this.viewMemoDialogVisable = true;
    }
  },

  computed: {},
  components: {
    headeBar,
    sidebar
  },
  created(){
    this.getTableData();
  }
}
